import 'package:flutter/material.dart';
import 'package:fantuike_app/constants.dart' show Constants;
import 'package:fantuike_app/api/Api.dart' show Api;
import 'package:dio/dio.dart';
import '../child_page/product_detail.dart';
import 'package:fantuike_app/router/slideRouter.dart';
import 'package:fluttertoast/fluttertoast.dart';

class StoreDetailPage extends StatefulWidget {
  @override
  _StoreDetailPageState createState() => _StoreDetailPageState();
}

class _StoreDetailPageState extends State<StoreDetailPage>
    with AutomaticKeepAliveClientMixin, SingleTickerProviderStateMixin {
  ScrollController _scrollController;
  TabController _tabController;

  PreferredSize BuildAppBarWidget() {
    return PreferredSize(
        child: AppBar(
          leading: IconButton(
              icon: Icon(
                Icons.chevron_left,
                size: 30.0,
                color: Color(0xffffffff),
              ),
              onPressed: () {
                Navigator.pop(context);
              }),
          backgroundColor: Color(0xfff26966),
          title: Text(
            "我的店铺",
            style: TextStyle(
                color: Color(
                  0xffffffff,
                ),
                fontSize: 18.0),
          ),
          centerTitle: true,
          elevation: 0.0,
          actions: <Widget>[
            IconButton(
                iconSize: 20.0,
                color: Color(0xffffffff),
                icon: Icon(
                    IconData(0xe648, fontFamily: Constants.IconFontFamily)),
                onPressed: () {
                  Fluttertoast.showToast(
                      msg: "开发中，敬请期待~",
                      toastLength: Toast.LENGTH_SHORT,
                      gravity: ToastGravity.BOTTOM,
                      fontSize: 14.0,
                      backgroundColor: Color(0xfff26966),
                      textColor: Color(0xffffffff));
                }),
            SizedBox(
              width: 5.0,
            )
          ],
        ),
        preferredSize:
        Size.fromHeight(MediaQuery
            .of(context)
            .size
            .height * 0.065));
  }

  @override
  void initState() {
    super.initState();
    _scrollController = new ScrollController(initialScrollOffset: 0.0);
    _tabController = TabController(length: 2, vsync: this);
    getProductList();
  }

  @override
  void dispose() {
    super.dispose();
    _scrollController.dispose();
    _tabController.dispose();
  }

  List creditCardList = [];
  List loanList = [];

  void getProductList() {
    _getProductList().then((result) {
      setState(() {
        creditCardList.addAll(result['extend']["creditList"]);
        loanList.addAll(result['extend']['loanList']);
      });
    });
  }

  Future _getProductList() async {
    try {
      String url = Api.getMyStoreOfProduct + "?userId=70";
      Response response = await Dio().get(url);
      return response.data;
    } catch (e) {}
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: BuildAppBarWidget(),
      body: NestedScrollView(
          headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
            return <Widget>[
              SliverAppBar(
                elevation: 5.0,
                leading: Text(""),
                pinned: true,
                floating: true,
                expandedHeight: 190.0,
                flexibleSpace: FlexibleSpaceBar(
                  collapseMode: CollapseMode.pin,
                  background: Container(
                    height: double.infinity,
                    child: Column(
                      children: <Widget>[_buildBanner()],
                    ),
                  ),
                ),
                bottom: TabBar(
                  controller: _tabController,
                  indicatorSize: TabBarIndicatorSize.tab,
                  labelColor: Color(0xfff26966),
                  indicatorColor: Color(0xfff26966),
                  unselectedLabelColor: Color(0xff000000),
                  tabs: <Widget>[
                    Tab(
                      text: "信用卡",
                    ),
                    Tab(
                      text: "贷款",
                    )
                  ],
                ),
              ),
            ];
          },
          body: TabBarView(controller: _tabController, children: [
            // 信用卡列表
            _buildCreditcardListView(creditCardList),
            // 贷款列表
            _buildLoanListView(loanList)
          ])),
    );
  }

  Widget _buildBanner() {
    return Container(
      alignment: Alignment.center,
      child: Image.asset(
        "assets/images/storePost.png",
        fit: BoxFit.fill,
      ),
    );
  }

  // 构造信用卡列表
  Widget _buildCreditcardListView(creditCardList) {
    List<Widget> tiles = [];
    for (var item in creditCardList) {
      tiles.add(Container(
        height: 100.0,
        decoration: BoxDecoration(
            boxShadow: <BoxShadow>[
              BoxShadow(
                color: const Color(0xffcccccc),
                blurRadius: 5.0,
                spreadRadius: 2.0,
                offset: Offset(-1.0, 3.0),
              )
            ],
            borderRadius: BorderRadius.all(Radius.circular(5.0)),
            color: Color(0xffffffff)),
        padding: const EdgeInsets.only(top: 6.0, bottom: 5.0),
        child: GestureDetector(
          onTap: () {
            Navigator.of(context).push(SlideRouter(ProductDetailPage(
                productId: item['productId'], productType: 0)));
          },
          child: Column(
            children: <Widget>[
              Expanded(
                child: Container(
                  child: Image.network(
                    item['productAvatar'],
                    fit: BoxFit.fill,
                  ),
                ),
                flex: 6,
              ),
              Expanded(
                child: Container(
                  child: Text(
                    item['productName'],
                    style: TextStyle(
                        fontSize: 15.0,
                        fontWeight: FontWeight.w500,
                        color: Color(0xff292929)),
                  ),
                ),
                flex: 2,
              ),
              Expanded(
                  child: Container(
                    padding: const EdgeInsets.only(
                        left: 7.0, right: 7.0, top: 1.0, bottom: 1.0),
                    child: Text(
                      "最高赚" + item['makeMoney'].toString() + "元",
                      style: TextStyle(
                          fontSize: 10.0, color: Color(0xfff5f5f5)),
                    ),
                    decoration: BoxDecoration(
                        color: Color(0xfff26966),
                        borderRadius: BorderRadius.all(Radius.circular(10.0))),
                  ))
            ],
          ),
        ),
      ));
    }

    return ListView(
      shrinkWrap: true,
      padding: const EdgeInsets.all(0.0),
      children: <Widget>[
        GridView.count(
            childAspectRatio: 4 / 5,
            mainAxisSpacing: 15.0,
            crossAxisSpacing: 10.0,
            padding: const EdgeInsets.only(
                top: 15.0, bottom: 10.0, left: 10.0, right: 10.0),
            physics: NeverScrollableScrollPhysics(),
            shrinkWrap: true,
            crossAxisCount: 3,
            children: tiles)
      ],
    );
  }

  // 构造贷款列表
  Widget _buildLoanListView(loanList) {
    List<Widget> tiles = [];

    for (var item in loanList) {
      tiles.add(Container(
        padding: const EdgeInsets.only(bottom: 5.0),
        alignment: Alignment.centerLeft,
        child: GestureDetector(
          onTap: () {
            print("111");
//            Navigator.of(context).push(SlideRouter(ProductDetailPage(
//                productId: item['productId'], productType: 1)));
            Navigator.of(context).push(MaterialPageRoute(
                builder: (BuildContext context) =>
                    ProductDetailPage(
                      productId: item['productId'], productType: 1)));
          },
          child: Column(
            children: <Widget>[
              Expanded(
                child: Container(
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      Container(
                        child: Row(
                          children: <Widget>[
                            Image.network(item['productAvatar']),
                            SizedBox(
                              width: 5.0,
                            ),
                            Text(
                              item['productName'],
                              style: TextStyle(fontSize: 15.0),
                            ),
                            SizedBox(
                              width: 3.0,
                            ),
                            Container(
                              margin: const EdgeInsets.only(top: 2.0),
                              padding: const EdgeInsets.only(
                                  left: 3.0, right: 3.0, top: 0.0, bottom: 0.0),
                              child: Text(
                                item['introduce'],
                                style: TextStyle(
                                    fontSize: 10.0, color: Color(0xfff26966)),
                              ),
                              decoration: BoxDecoration(
                                  border: Border.all(color: Color(0xfff26966)),
                                  borderRadius:
                                  BorderRadius.all(Radius.circular(5.0))),
                            )
                          ],
                        ),
                      ),
                      Container(
                        alignment: Alignment.centerRight,
                        child: Row(
                          children: <Widget>[
                            Text(
                              "借款期限:",
                              style: TextStyle(
                                  color: Color(0xff646464), fontSize: 12.0),
                            ),
                            Text(
                              item['timeLimit'],
                              style: TextStyle(
                                  fontWeight: FontWeight.bold, fontSize: 16.0),
                            )
                          ],
                        ),
                      )
                    ],
                  ),
                ),
                flex: 1,
              ),
              Expanded(
                child: Container(
                  margin: const EdgeInsets.only(top: 10.0),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      Container(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                          children: <Widget>[
                            Text(
                              item['highestLines'].toString(),
                              style: TextStyle(
                                  color: Color(0xffF3B062), fontSize: 20.0),
                            ),
                            Text(
                              "贷款额度(元)",
                              style: TextStyle(color: Color(0xff646464)),
                            ),
                          ],
                        ),
                      ),
                      Container(
                        alignment: Alignment.bottomCenter,
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: <Widget>[
                                Text(
                                  "月利率: ",
                                  style: TextStyle(
                                      color: Color(0xff767676), fontSize: 13.0),
                                ),
                                Text(
                                  item['interestRate'],
                                  style: TextStyle(fontSize: 15.0),
                                ),
                                Text(
                                  "%",
                                  style: TextStyle(fontSize: 15.0),
                                )
                              ],
                            ),
                            Row(
                              children: <Widget>[
                                Text(
                                  "通过率: ",
                                  style: TextStyle(
                                      color: Color(0xff767676), fontSize: 13.0),
                                ),
                                Text(
                                  item['passRate'],
                                  style: TextStyle(fontSize: 15.0),
                                ),
                              ],
                            )
                          ],
                        ),
                      ),
                      Container(
                        alignment: Alignment.center,
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: <Widget>[
                            Row(
                              children: <Widget>[
                                Text(
                                  "最高赚:",
                                  style: TextStyle(
                                      color: Color(0xfff26966), fontSize: 13.0),
                                ),
                                Text(
                                  item['makeMoney'] == 0
                                      ? (double.parse(item['price']) * 100)
                                      .toString() +
                                      "%"
                                      : item['makeMoney'].toString() + "元",
                                  style: TextStyle(
                                      color: Color(0xfff26966), fontSize: 18.0),
                                )
                              ],
                            )
                          ],
                        ),
                      )
                    ],
                  ),
                ),
                flex: 2,
              ),
            ],
          ),
        ),
        decoration: BoxDecoration(
            border: Border(
                bottom: BorderSide(width: 1.0, color: Color(0xffeeeeee)))),
      ));
    }

    return ListView(
      shrinkWrap: true,
      padding: const EdgeInsets.only(top: 5.0),
      children: <Widget>[
        GridView.count(
          childAspectRatio: 8 / 2,
          mainAxisSpacing: 10.0,
          padding: const EdgeInsets.all(14.0),
          physics: NeverScrollableScrollPhysics(),
          shrinkWrap: true,
          crossAxisCount: 1,
          children: tiles,
        )
      ],
    );
  }

  @override
  bool get wantKeepAlive => true;
}
